// 中间件
const { resolve } = require('path')

const jwt = require('jsonwebtoken')

const { baseRouter, SECRET } = require(resolve(__dirname, '../config/default'))
const { jgcl } = require(resolve(__dirname, '../utils/utils'))


// 验证token
const verifyToken = async (ctx, next) => {

  let token = ctx.request.headers.authorization

  if (token) {
    try {
      token = token.slice(7)
      jwt.verify(token, SECRET)
      await next()
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        jgcl(ctx, 207, 'token 过期请重新登陆!')
      } else if (err.name === 'JsonWebTokenError') {
        jgcl(ctx, 208, '无效的token!')
      }
    }
  } else {
    ctx.body = ctx.body = {
      status: {
        code: 206,
        msg: 'token 不存在，请登录!'
      },
      data: null
    }
  }

}

module.exports = {
  verifyToken
}